/*
 * Copyright (C) 2001-2007 Jacek Sieka, arnetheduck on gmail point com
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include "stdafx.h"
#include "../client/DCPlusPlus.h"
#include "Resource.h"
#include "Mainfrm.h"

#include "RSSnewsFrame.h"
#include "../client/File.h"

int RSSNewsFrame::columnIndexes[] = { COLUMN_TITLE, COLUMN_URL, COLUMN_DESC, COLUMN_DATE, COLUMN_AUTHOR, COLUMN_CATEGORY, COLUMN_SOURCE };

int RSSNewsFrame::columnSizes[] = { 100, 110, 290, 125, 80, 80, 80 };


LRESULT RSSNewsFrame::OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
	CreateSimpleStatusBar(ATL_IDS_IDLEMESSAGE, WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | SBARS_SIZEGRIP);
	ctrlStatus.Attach(m_hWndStatusBar);
	
	ctrlList.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN |
	                WS_HSCROLL | WS_VSCROLL | LVS_REPORT | LVS_SHOWSELALWAYS | LVS_SHAREIMAGELISTS | LVS_SINGLESEL, WS_EX_CLIENTEDGE, IDC_RSS);
	ctrlList.SetExtendedListViewStyle(LVS_EX_LABELTIP | LVS_EX_HEADERDRAGDROP | LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER | 0x00010000 | LVS_EX_INFOTIP | (BOOLSETTING(VIEW_GRIDCONTROLS) ? LVS_EX_GRIDLINES : 0));
	
	ctrlList.SetImageList(WinUtil::fileImages, LVSIL_SMALL);
	ctrlList.SetBkColor(WinUtil::bgColor);
	ctrlList.SetTextBkColor(WinUtil::bgColor);
	ctrlList.SetTextColor(WinUtil::textColor);
	
	// Create listview columns
	WinUtil::splitTokens(columnIndexes, SETTING(RSS_COLUMNS_ORDER), COLUMN_LAST);
	WinUtil::splitTokens(columnSizes, SETTING(RSS_COLUMNS_WIDTHS), COLUMN_LAST);
	
	for (uint8_t j = 0; j < COLUMN_LAST; j++)
	{
		int fmt = (j == COLUMN_DATE) ? LVCFMT_RIGHT : LVCFMT_LEFT;
		ctrlList.InsertColumn(j, CTSTRING_I(rss_columnNames[j]), fmt, columnSizes[j], j);
	}
	
	ctrlList.setColumnOrderArray(COLUMN_LAST, columnIndexes);
	ctrlList.setVisible(SETTING(RSS_COLUMNS_VISIBLE));
	ctrlList.setSortColumn(COLUMN_DATE);
	UpdateLayout();
	
	
	SettingsManager::getInstance()->addListener(this);
	RSSManager::getInstance()->addListener(this);
	
	RSSManager::getInstance()->UpdateFeeds();
	
	updateList(RSSManager::getInstance()->lockNewsList());
	RSSManager::getInstance()->unlockNewsList();
	
	// SSA: Here sets URL, and TimeUpdate
	//string tmp;
	//try {
	//    tmp = File(Util::getNotepadFile(), File::READ, File::OPEN).read();
	//} catch(const FileException&) {
	//    // ...
	//}
	//if(tmp.empty()) {
	//    tmp = SETTING(NOTEPAD_TEXT);
	//    if(!tmp.empty()) {
	//        dirty = true;
	//        SET_SETTING(NOTEPAD_TEXT, Util::emptyString);
	//    }
	//}
	
	//ctrlPad.SetWindowText(Text::toT(tmp).c_str());
	//ctrlPad.EmptyUndoBuffer();
	//ctrlClientContainer.SubclassWindow(ctrlPad.m_hWnd);
	
	bHandled = FALSE;
	return TRUE;
}

LRESULT
RSSNewsFrame::updateList(const RSSManager::NewsList& list)
{
	ctrlList.SetRedraw(FALSE);
	for (RSSManager::NewsIter i = list.begin(); i != list.end(); ++i)
	{
		addEntry(*i);
	}
	ctrlList.SetRedraw(TRUE);
	ctrlList.Invalidate();
	
	return 1;
}
LRESULT RSSNewsFrame::onClose(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{

	if (!closed)
	{
		RSSManager::getInstance()->removeListener(this);
		SettingsManager::getInstance()->removeListener(this);
		
		closed = true;
		WinUtil::setButtonPressed(IDC_RSS, false);
		PostMessage(WM_CLOSE);
		return 0;
	}
	else
	{
		ctrlList.saveHeaderOrder(SettingsManager::RSS_COLUMNS_ORDER, SettingsManager::RSS_COLUMNS_WIDTHS, SettingsManager::RSS_COLUMNS_VISIBLE);
		
		//frame = NULL; [-] IRainman see template StaticFrame in WinUtil.h
		
		ctrlList.DeleteAndCleanAllItems();
		
		bHandled = FALSE;
		return 0;
	}
}

void RSSNewsFrame::UpdateLayout(BOOL bResizeBars /*= TRUE*/)
{
	RECT rect;
	GetClientRect(&rect);
	
	// position bars and offset their dimensions
	UpdateBarsPosition(rect, bResizeBars);
	
	if (ctrlStatus.IsWindow())
	{
		CRect sr;
		int w[4];
		ctrlStatus.GetClientRect(sr);
		w[3] = sr.right - 16;
		w[2] = max(w[3] - 100, 0);
		w[1] = max(w[2] - 100, 0);
		w[0] = max(w[1] - 100, 0);
		
		ctrlStatus.SetParts(4, w);
	}
	
	CRect rc(rect);
	ctrlList.MoveWindow(rc);
	
}

//LRESULT RSSNewsFrame::onLButton(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled) {
//  HWND focus = GetFocus();
//  bHandled = false;
//  if(focus == ctrlPad.m_hWnd) {
//      POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
//      tstring x;
//      tstring::size_type start = (tstring::size_type)WinUtil::textUnderCursor(pt, ctrlPad, x);
//      tstring::size_type end = x.find(_T(" "), start);
//
//      if(end == string::npos)
//          end = x.length();
//
//      bHandled = WinUtil::parseDBLClick(x, start, end);
//  }
//  return 0;
//}

void RSSNewsFrame::on(SettingsManagerListener::Save, SimpleXML& /*xml*/) noexcept
{
	bool refresh = false;
	if (ctrlList.GetBkColor() != WinUtil::bgColor)
	{
		ctrlList.SetBkColor(WinUtil::bgColor);
		ctrlList.SetTextBkColor(WinUtil::bgColor);
		refresh = true;
	}
	if (ctrlList.GetTextColor() != WinUtil::textColor)
	{
		ctrlList.SetTextColor(WinUtil::textColor);
		refresh = true;
	}
	if (refresh == true)
	{
		RedrawWindow(NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
	}
}
void
RSSNewsFrame::on(RSSListener::NewRSS, const int & newsCount) noexcept
{
	if ((BOOLSETTING(POPUP_NEW_RSSNEWS)) && (!BOOLSETTING(POPUPS_DISABLED)))
	{
		MainFrame::getMainFrame()->ShowBalloonTip(Text::toT(m_Message).c_str(), CTSTRING(NEW_RSS_NEWS));
	}
	m_Message = Util::emptyString;
}

void RSSNewsFrame::on(RSSListener::Added, RSSItem* item) noexcept
{
	addEntry(item);
	m_Message = item->getTitle() + " - " + item->getSource() + "\r\n";
}

LRESULT RSSNewsFrame::onDoubleClick(int /*idCtrl*/, LPNMHDR pnmh, BOOL& /*bHandled*/)
{
	NMITEMACTIVATE * const item = (NMITEMACTIVATE*) pnmh;
	
	if (item->iItem != -1)
	{
		RSSItemInfo *ii = ctrlList.getItemData(item->iItem);
		WinUtil::openFile(Text::toT(ii->entry->getUrl()));
	}
	return 0;
}

/**
 * @file
 * $Id: RSSnewsFrame.cpp 7998 2011-08-24 10:49:04Z tret2003 $
 */
